<template>
  <div>
    <h1>项目管理页面</h1>
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="请输入项目名称"
          clearable
          class="search-input"
        />
        <el-button type="primary" @click="fetchProjects">搜索</el-button>
        <el-button type="success" @click="openCreateDialog">创建项目</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table :data="projects" border style="width: 100%" v-loading="loading">
        <el-table-column prop="projectName" label="项目名称" />
        <el-table-column prop="startTime" label="开始时间" />
        <el-table-column prop="endTime" label="结束时间" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="progress" label="进度" width="100">
          <template #default="scope">
            <el-progress :percentage="scope.row.progress" />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="teamName" label="团队名称" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              v-if="roleId === 1 || roleId === 2 || roleId === 3"
              type="primary"
              size="small"
              @click="openEditDialog(scope.row)"
            >
              修改
            </el-button>
            <el-button
              v-if="roleId === 1 || roleId === 2 || roleId === 3"
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
<el-dialog v-model="editDialogVisible" title="修改项目">
  <el-form :model="editForm" label-width="100px">
    <el-form-item label="项目名称">
      <el-input v-model="editForm.projectName" placeholder="请输入项目名称" />
    </el-form-item>
    <el-form-item label="开始时间">
      <el-date-picker
        v-model="editForm.startTime"
        type="datetime"
        placeholder="选择开始时间"
        format="YYYY-MM-DD HH:mm:ss"
      />
    </el-form-item>
    <el-form-item label="结束时间">
      <el-date-picker
        v-model="editForm.endTime"
        type="datetime"
        placeholder="选择结束时间"
        format="YYYY-MM-DD HH:mm:ss"
      />
    </el-form-item>
    <el-form-item label="描述">
      <el-input
        type="textarea"
        v-model="editForm.description"
        rows="4"
        placeholder="请输入描述"
      />
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model="editForm.status" placeholder="选择状态">
        <el-option label="未开始" value="1"></el-option>
        <el-option label="进行中" value="2"></el-option>
        <el-option label="已完成" value="3"></el-option>
        <el-option label="已逾期" value="4"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="团队">
      <el-button type="primary" @click="openTeamDialog">选择团队</el-button>
      <span>{{ selectedTeamName }}</span>
    </el-form-item>
    <el-form-item label="进度">
      <span>{{ editForm.progress }}%</span>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submitEdit">保存</el-button>
  </div>
</el-dialog>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
  background
  layout="prev, pager, next, jumper"
  :total="total"
  :page-size="pageSize"
  :current-page="currentPage"
  @current-change="handlePageChange"
  :pager-count="5"
  :page-sizes="[10, 20, 30, 50]"
/>
      </div>
    </el-card>
  <el-button type="warning" @click="exportProjects">导出</el-button>
    <!-- 创建项目弹窗 -->
    <el-dialog v-model="createDialogVisible" title="创建项目">
      <el-form :model="createForm" label-width="100px">
        <el-form-item label="项目名称">
          <el-input v-model="createForm.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="createForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="createForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            type="textarea"
            v-model="createForm.description"
            rows="4"
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-input v-model="createForm.status" disabled placeholder="未开始" />
        </el-form-item>
        <el-form-item label="团队">
          <el-button type="primary" @click="openTeamDialog">选择团队</el-button>
          <span>{{ selectedTeamName }}</span>
        </el-form-item>
        <el-form-item label="资源分配">
          <el-button type="primary" @click="openResourceDialog">分配资源</el-button>
          <ul>
            <li v-for="(resource, index) in createForm.resourceAllocations" :key="index">
              {{ resource.resourceName }} - 分配数量: {{ resource.allocatedQuantity }}
            </li>
          </ul>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreate">保存</el-button>
      </div>
    </el-dialog>

    <!-- 选择团队弹窗 -->
    <el-dialog v-model="teamDialogVisible" title="选择团队">
      <el-table :data="teams" border style="width: 100%" @row-click="selectTeam">
        <el-table-column prop="id" label="团队ID" width="80" />
        <el-table-column prop="teamname" label="团队名称" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="teamDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 分配资源弹窗 -->
    <el-dialog v-model="resourceDialogVisible" title="分配资源">
      <el-table :data="resources" border style="width: 100%">
        <el-table-column prop="resourceName" label="资源名称" />
        <el-table-column prop="resourceType" label="资源类型" />
        <el-table-column prop="quantity" label="可用数量" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column label="分配数量">
          <template #default="scope">
            <el-input
              type="number"
              v-model="resourceAllocations[scope.$index].allocatedQuantity"
              placeholder="输入分配数量"
            />
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resourceDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="confirmResourceAllocation">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import axios from 'axios';
// import { ElMessage } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus'; // 引入 ElMessageBox
import dayjs from 'dayjs';
// 弹窗状态
const createDialogVisible = ref(false);
const teamDialogVisible = ref(false); // 控制团队选择弹窗的显示状态
const resourceDialogVisible = ref(false);
// 修改项目弹窗状态
const editDialogVisible = ref(false);

// 修改项目表单
const editForm = reactive({
  id: null,
  projectName: '',
  startTime: '',
  endTime: '',
  description: '',
  status: null,
  teamId: null,
  progress: null,
});

// 打开修改项目弹窗
const openEditDialog = (project) => {
  Object.assign(editForm, project); // 将项目数据赋值给 editForm
  selectedTeamName.value = project.teamName || '未指定'; // 设置团队名称
  editDialogVisible.value = true; // 显示弹窗
};

// 提交修改项目
const submitEdit = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    await axios.put(
      'http://localhost:8080/project/update',
      {
        id: editForm.id,
        projectName: editForm.projectName,
        startTime: editForm.startTime
          ? dayjs(editForm.startTime).format('YYYY-MM-DDTHH:mm:ss')
          : null,
        endTime: editForm.endTime
          ? dayjs(editForm.endTime).format('YYYY-MM-DDTHH:mm:ss')
          : null,
        description: editForm.description,
        status: editForm.status,
        teamId: editForm.teamId,
        progress: editForm.progress,
      },
      {
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
      }
    );

    ElMessage.success('项目修改成功');
    editDialogVisible.value = false;
    fetchProjects(); // 刷新项目列表
  } catch (error) {
    console.error('修改项目失败:', error);
    ElMessage.error('修改项目失败，请稍后重试');
  }
};
const getStatusText = (status) => {
  switch (status) {
    case 1:
      return '未开始';
    case 2:
      return '进行中';
    case 3:
      return '已完成';
    case 4:
      return '已逾期';
    default:
      return '未知状态';
  }
};

// 获取状态标签类型
const getStatusTag = (status) => {
  switch (status) {
    case 1:
      return 'info'; // 未开始
    case 2:
      return 'success'; // 进行中
    case 3:
      return 'warning'; // 已完成
    case 4:
      return 'danger'; // 已逾期
    default:
      return 'default'; // 未知状态
  }
};
// 删除项目
const handleDelete = async (project) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    // 确认删除操作
    await ElMessageBox.confirm(
      `确定要删除项目 "${project.projectName}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 调用删除接口
    await axios.delete(`http://localhost:8080/project/${project.id}`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
const total = ref(0);           // 数据总数
const pageSize = ref(10);       // 每页大小
const currentPage = ref(1);     // 当前页码

    ElMessage.success('项目删除成功');
    fetchProjects(); // 刷新项目列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除项目失败:', error);
      ElMessage.error('删除项目失败，请稍后重试');
    }
  }
};
// 创建表单
const createForm = reactive({
  projectName: '',
  startTime: '',
  endTime: '',
  description: '',
  status: 1, // 默认未开始
  teamId: null,
  resourceAllocations: [],
});

// 团队数据
const teams = ref([]);
const selectedTeamName = ref('');

// 资源数据
const resources = ref([]);
const resourceAllocations = reactive([]);

// 项目列表数据
const projects = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const loading = ref(false);
const searchQuery = ref('');
const roleId = parseInt(localStorage.getItem('roleId'), 10); // 从 localStorage 获取 roleId

// 打开创建项目弹窗
const openCreateDialog = () => {
  createDialogVisible.value = true;
};
const exportProjects = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    const response = await axios.get('http://localhost:8080/project/report/export', {
      headers: {
        Authorization: `Bearer ${token}`,
        Accept: '*/*',
      },
      responseType: 'blob', // 确保返回的是二进制数据
    });

    // 创建 Blob 对象并触发下载
    const blob = new Blob([response.data], { type: response.headers['content-type'] });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;

    // 设置下载文件名
    const contentDisposition = response.headers['content-disposition'];
    const fileName = contentDisposition
      ? contentDisposition.split('filename=')[1]
      : 'exported_projects.xlsx';
    link.download = decodeURIComponent(fileName);

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请稍后重试');
  }
};
// 打开团队选择弹窗
const openTeamDialog = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }
    const response = await axios.get('http://localhost:8080/team/all', {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    teams.value = response.data.data;
    teamDialogVisible.value = true;
  } catch (error) {
    console.error('获取团队数据失败:', error);
    ElMessage.error('获取团队数据失败，请稍后重试');
  }
};

// 选择团队
const selectTeam = (team) => {
  if (createDialogVisible.value) {
    // 如果是创建项目弹窗
    createForm.teamId = team.id;
  } else if (editDialogVisible.value) {
    // 如果是修改项目弹窗
    editForm.teamId = team.id;
  }
  selectedTeamName.value = team.teamname; // 更新团队名称
  teamDialogVisible.value = false; // 关闭弹窗
};

// 打开资源分配弹窗
const openResourceDialog = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }
    const response = await axios.get('http://localhost:8080/resource/list', {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    resources.value = response.data.data;
    resourceAllocations.splice(0, resourceAllocations.length, ...resources.value.map((resource) => ({
      resourceId: resource.id,
      resourceName: resource.resourceName,
      allocatedQuantity: 0,
    })));
    resourceDialogVisible.value = true;
  } catch (error) {
    console.error('获取资源数据失败:', error);
    ElMessage.error('获取资源数据失败，请稍后重试');
  }
};

// 确认资源分配
const confirmResourceAllocation = () => {
  createForm.resourceAllocations = resourceAllocations.filter(
    (allocation) => allocation.allocatedQuantity > 0
  );
  resourceDialogVisible.value = false;
};

// 提交创建项目
const submitCreate = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }
    await axios.post(
      'http://localhost:8080/project/create',
      {
        projectName: createForm.projectName,
        startTime: createForm.startTime,
        endTime: createForm.endTime,
        description: createForm.description,
        status: createForm.status,
        teamId: createForm.teamId,
        resourceAllocations: createForm.resourceAllocations.map((allocation) => ({
          resourceId: allocation.resourceId,
          allocatedQuantity: allocation.allocatedQuantity,
        })),
      },
      {
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
      }
    );
    ElMessage.success('项目创建成功');
    createDialogVisible.value = false;
    fetchProjects(); // 刷新项目列表
  } catch (error) {
    console.error('创建项目失败:', error);
    ElMessage.error('创建项目失败，请稍后重试');
  }
};

// 获取项目列表
const fetchProjects = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    const response = await axios.get('http://localhost:8080/project/page', {
      params: {
        current: currentPage.value,
        size: pageSize.value,
        projectName: searchQuery.value || undefined,
      },
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    projects.value = response.data.records; // 后端返回的分页数据
    total.value = response.data.total;     // 总记录数
    const { records, total: totalRecords } = response.data.data;

    projects.value = records.map((project) => ({
      ...project,
      startTime: project.startTime ? dayjs(project.startTime).format('YYYY-MM-DD') : '未设置',
      endTime: project.endTime ? dayjs(project.endTime).format('YYYY-MM-DD') : '未设置',
    }));

    total.value = totalRecords;
  } catch (error) {
    console.error('获取项目数据失败:', error);
    ElMessage.error('获取项目数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchProjects();
};

// 页面加载时获取数据
fetchProjects();
</script>

<style scoped>
.box-card {
  margin: 20px;
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>

<style scoped>
.box-card {
  margin: 20px;
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>

<style scoped>
.box-card {
  margin: 20px;
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>

<style scoped>
.box-card {
  margin: 20px;
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
